package com.shigen.demo.shorturl.util;

/**
 * @author shigenfu
 * @date 2023/10/14 14:26
 */

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 短链接生成工具类
 *
 * @author shigenfu
 */
public class ShortLinkUtils {

    private static final String CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int LINK_LENGTH = 6;

    /**
     * 生成短链接
     *
     * @param longLink 原始长链接
     * @return 短链接
     */
    public static String generateShortLink(String longLink) {
        // 使用MD5哈希函数生成长链接的哈希值
        String hash = md5Hash(longLink);
        StringBuilder shortLink = new StringBuilder();

        for (int i = 0; i < LINK_LENGTH; i++) {
            int index = Integer.parseInt(hash.substring(i * 4, i * 4 + 4), 16);
            shortLink.append(CHARSET.charAt(index % CHARSET.length()));
        }

        return shortLink.toString();
    }

    /**
     * 对输入字符串进行MD5哈希
     *
     * @param input 输入字符串
     * @return MD5哈希值
     */
    private static String md5Hash(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes());

            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
}

